<template>
  <div class="page-container">
    <div class="in-container">
      <AppSearchForm @submit="search()" @reset="reset()">
        <el-form-item>
          <el-input
            v-model="query.name"
            clearable
            placeholder="输入抬头类型模糊搜索"
            style="width: 200px"
          />
        </el-form-item>
      </AppSearchForm>
      <div class="nav-tab">
        <el-button @click="openNewDialog" type="primary"> 新增 </el-button>
        <el-button @click="deleteSelectData" type="danger"> 删除 </el-button>
      </div>
      <AppPageTable
        stripe
        :data="tableData.data"
        @change="getTableData()"
        :autostyle="'height:calc(100% - 64px) ;'"
        :option="tableData.option"
      >
        <el-table-column show-overflow-tooltip type="selection" width="40" fixed="left"/>
        <el-table-column prop="entName" width="140" label="客户简称" />
        <el-table-column prop="type" width="120" label="收发通类型">
          <template #default="scope">
            {{ parseType(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="title" width="240" label="抬头类型" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button @click="update(scope.row)"  type="primary">编辑</el-button>
            <el-popconfirm
              title="确定删除本条数据吗？"
              @confirm="deleteData(scope.row)"
            >
              <template #reference>
                <el-button  type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </AppPageTable>
      <el-dialog
        v-model="dialogData.show"
        :title="dialogData.title"
        width="30%"
      >
        <el-form
          :model="formData"
          :rules="formRules"
          ref="form"
          label-width="100px"
        >
          <el-form-item label="客户简称" prop="entId">
            <el-select
              v-model="formData.entId"
              filterable
              remote
              clearable
              :remote-show-suffix="true"
              :remote-method="select"
              :loading="selectLoading"
              @click="handleSelectClick"
              @clear="handleSelectClear"
              ref="select"
            >
              <el-option
                v-for="item in selectOption"
                :key="item.id"
                :label="item.label"
                :value="item.value"
                @click="handleOptionClick(item)"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="收发通类型" prop="type">
            <el-select v-model="formData.type">
              <el-option :value="1" label="发货人" />
              <el-option :value="2" label="收货人" />
              <el-option :value="3" label="通知人" />
              <el-option :value="4" label="海外代理" />
              <el-option :value="5" label="第二通知人" />
            </el-select>
          </el-form-item>
          <el-form-item label="抬头信息" prop="title">
            <el-input v-model="formData.title" type="textarea"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancel" link>取消</el-button>
            <el-button
              type="primary"
              @click="submit"
              :loading="dialogData.btnLoading"
            >
              确认
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { defineComponent } from "vue";
import AppSearchForm from "@/components/AppSearchForm.vue";
import AppPageTable, { useTableOption } from "@/components/AppPageTable2";
import { ElMessageBox } from 'element-plus';

export default defineComponent({
  components: {
    AppSearchForm,
    AppPageTable,
  },
  data() {
    return {
      tableData: {
        data: [],
        option: useTableOption(),
      },
      dialogData: {
        show: false,
        btnLoading: false,
        title: "",
      },
      formData: {
        entId: null,
        type: null,
        title: "",
      },
      formRules: {
        entId: [{ required: true, message: "请选择客户简称", trigger: "blur" }],
        type: [
          { required: true, message: "请选择收发通类型", trigger: "blur" },
        ],
      },
      query: {
        name: "",
      },
      selectOption: [],
      selectLoading: false,
      selectClickLabel: "",
    };
  },
  methods: {
    parseType(data) {
      if (data == "1") {
        return "发货人";
      } else if (data == "2") {
        return "收货人";
      } else if (data == "3") {
        return "通知人";
      } else if (data == "4") {
        return "海外代理";
      }
    },
    handleSelectClick() {
      this.select(this.selectClickLabel);
    },
    handleSelectClear(){
      this.selectClickLabel=""
    },
    handleOptionClick(data) {
      this.selectClickLabel = data.label;
    },
    /**
     * 通过id去重
     * @param {*} arr 
     */
    uniqueById(arr) {
      let seenIds = {}; // 用于存储已经出现过的ID
      let result = [];

      for (let i = 0; i < arr.length; i++) {
        let item = arr[i];
        let itemId = item.id;

        // 如果ID尚未出现过，则将其添加到结果数组和已经出现过的ID列表中
        if (!seenIds[itemId]) {
          result.push(item);
          seenIds[itemId] = true;
        }
      }

      return result;
    },
    select(query) {
      this.selectLoading = true;
      this.$http
        .get("/api/buenterprise/query", {
          PageIndex: 1,
          PageSize: 20,
          KeyWords: query,
        })
        .then((res) => {
          this.selectOption = this.uniqueById(res.content).map((t) => {
            return {
              id: t.id,
              value: t.id,
              label: t.entName,
            };
          });
        })
        .finally(() => (this.selectLoading = false));
    },
    search() {
      this.tableData.option.page = 1;
      this.tableData.option.pageSize = 10;
      this.getTableData();
    },
    reset() {
      this.tableData.option.page = 1;
      this.tableData.option.pageSize = 10;
      this.query = {
        name: "",
      };
      this.search();
    },
    openNewDialog() {
      this.dialogData.title = "新增收发通";
      this.dialogData.show = true;
    },
    getTableData() {
      this.tableData.option.loading = true;
      this.$http
        .get("/api/bubltitlehistory/query", {
          Title: this.query.name,
          PageIndex: this.tableData.option.page,
          PageSize: this.tableData.option.pageSize,
        })
        .then((res) => {
          this.tableData.data = res.content;
          this.tableData.option.total = res.totalElements;
        })
        .finally(() => {
          this.tableData.option.loading = false;
        });
    },
    update(data) {
      this.formData = JSON.parse(JSON.stringify(data));
      this.selectOption = [
        {
          id: data.entId,
          value: data.entId,
          label: data.entName,
        },
      ];
      this.selectClickLabel = data.entName;
      this.dialogData.title = "修改收发通";
      this.dialogData.show = true;
    },

    submit() {
      let url = "";
      if (this.formData.id) {
        url = "/api/bubltitlehistory/edit";
      } else {
        url = "/api/bubltitlehistory/create";
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.dialogData.btnLoading = true;
          this.$http
            .post(url, this.formData)
            .then((res) => {
              if (res.status) {
                this.$message.success(res.message);
                this.getTableData();
                this.dialogData.show = false;
              } else {
                this.$message.error(res.message);
              }
            })
            .finally(() => (this.dialogData.btnLoading = false));
        }
      });
    },
    cancel() {
      this.dialogData.show = false;
    },
    deleteData(data) {
      this.$http
        .post("/api/bubltitlehistory/delete", {
          idArray: [data.id],
        })
        .then((res) => {
          if (res.status) {
            this.$message.success(res.message);
            this.getTableData();
          } else {
            this.$message.error(res.message);
          }
        });
    },
    deleteSelectData() {
      let deleteSelectArray = [];
      this.tableData.option.selected.forEach((t) => deleteSelectArray.push(t.id));
      ElMessageBox.confirm("确定删除所选信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          this.$http
            .post("/api/bubltitlehistory/delete", {
              idArray: deleteSelectArray,
            })
            .then((res) => {
              if (res.status) {
                this.$message.success(res.message);
                this.getTableData();
              } else {
                this.$message.error(res.message);
              }
            });
        })
        .catch(() => {
          this.$message.info("取消删除");
        });
    },
  },
  watch: {
    "dialogData.show"(newVal) {
      if (!newVal) {
        this.formData = {
          entId: null,
          type: null,
          title: "",
        };
        this.$nextTick(() => {
          // this.$refs.form.resetFields();
          this.$refs.form.clearValidate();
        });
      }
    },
  },
  mounted() {
    this.getTableData();
  },
});
</script>

<style lang="scss" scoped>
.nav-tab {
  margin-bottom: 8px;
}
</style>
